"""
常见问题配置
"""
import logging

from biz.core.thanos.models import CommonProblem
from biz.exceptions import ERROR_DATA_NOT_EXISTS
from gis.common.django_ext.models import paginate
from gis.common.exceptions import BizException

_LOGGER = logging.getLogger(__name__)


def list_common_problem(pro_id, page_no, page_size, type_id=None):
    assert page_no > 0
    assert page_size > 0
    query = CommonProblem.objects.filter(pro_id=pro_id).all()
    if type_id:
        query = query.filter(type_id=type_id)
    return query.count(), [e.to_dict() for e in paginate(query, page_no, page_size)]


def add_common_problem(pro_id, type_id, title, answer):
    data = CommonProblem.objects.create(type_id=type_id, title=title, answer=answer, pro_id=pro_id)
    return data.to_dict()


def get_common_problem(data_id):
    data = _get_data(data_id)
    return data.to_dict()


def update_common_problem(data_id, type_id, title, answer):
    data = _get_data(data_id)
    data.type_id = type_id
    data.title = title
    data.answer = answer
    data.save()
    return data.to_dict()


def delete_common_problem(data_id):
    assert data_id
    data = _get_data(data_id)
    data.delete()


def _get_data(data_id):
    assert data_id > 0
    data = CommonProblem.objects.filter(pk=data_id).first()
    if not data:
        raise BizException(ERROR_DATA_NOT_EXISTS)
    return data
